import axios, { AxiosResponse } from "axios";
import Response from "../model/Reponse"


/**
 * 服务器的基地址
 */
export const BASE_URL = "http://192.168.31.128:8082";
export const MOCK_URL = 'http://127.0.0.1:4523/mock/722434'

export function mockRes<T>(data: T): Promise<T> {
    return new Promise((resolve) => {
        resolve(data);
    })
}

export function mockFail(): Promise<Boolean> {
    return new Promise((_resolve, reject) => {
        reject(false);
    })
}
/**
 * 对响应进行统一解析的函数
 * @param request - Axios请求对象
 */
export function resolve<DataType>(request: Promise<AxiosResponse<Response<any>>>) {
    return new Promise<DataType>((resolve, reject) => {
        request.then(resp => {
            if (resp.data.code === undefined && resp.data.data === undefined) {
                //@ts-ignore
                resolve(resp.data);
            } else if (resp.data.code === 200) {
                resolve(resp.data.data);
            } else {
                console.log(resp.data.message);
                reject(resp.data.message || "未知信息的异常");
            }
        }).catch(err => {
            console.log(err);
            reject(err.response.data.msg || err);
        });
    });
}

/**
 * 处理下载
 * @param response 处理响理
 */
export function convertResponseToBlob(response: AxiosResponse, filename?: string) {
    // 提取文件名
    let matched = response.headers['content-disposition'].match(/fileName=("(.*?)"|(.*))/);
    console.log(matched);
    let fileName = filename || "download"
    if (filename === undefined && matched !== null) {
        fileName = matched[2] || matched[3];
    }
    // 将二进制流转为blob
    const blob = new Blob([response.data], { type: 'application/octet-stream' })
    if (typeof (window as any).navigator.msSaveBlob !== 'undefined') {
        // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
        (window as any).navigator.msSaveBlob(blob, decodeURI(fileName))
    } else {
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(blob)
        // 创建a标签，用于跳转至下载链接
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', decodeURI(fileName))
        // 兼容：某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
        }
        // 挂载a标签
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL)
    }
}

/**
 * 发送HTTP请求的对象
 */
const axiosInstance = axios.create({
    // baseURL: BASE_URL,
    timeout: 100000,
    withCredentials: true,
    headers: {
        'Access-Control-Allow-Headers': 'x-requested-with,content-type'
    }
});

/**
 * 配置拦截器
 */
axiosInstance.interceptors.request.use(function (config) {
    config.url = "/api" + config.url

    // 如果没有认证，则主动添加认证信息
    // if (config.headers !== undefined) {
    //     if (!('token' in config.headers || 'token' in config.headers)) {
    //         const tokenType = "Bearer";
    //         const tokenValue = localStorage.getItem("token")

    //         config.headers.token = `${tokenType} ${tokenValue} `;

    //         // console.log(config)
    //     }
    // }

    return config;
},
    function (error) {
        // Do something with request error
        return Promise.reject(error);
    });

// Add a response interceptor
axiosInstance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, async function (error) {
    console.log(error)
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

export default axiosInstance;